package com.cloudkeeper.leasing.identity.controller.impl;

import com.cloudkeeper.leasing.base.model.Result;
import com.cloudkeeper.leasing.identity.controller.KPIVillageQuotaController;
import com.cloudkeeper.leasing.identity.domain.*;
import com.cloudkeeper.leasing.identity.dto.kpievaluation.KPIEvaluationDTO;
import com.cloudkeeper.leasing.identity.dto.kpivillagequota.KPIVillageQuotaDTO;
import com.cloudkeeper.leasing.identity.dto.kpivillagequota.KPIVillageQuotaSearchable;
import com.cloudkeeper.leasing.identity.dto.kpivillagequota.ScoringDTO;
import com.cloudkeeper.leasing.identity.service.*;
import com.cloudkeeper.leasing.identity.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.lang.NonNull;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nonnull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 村考核指标 controller
 * @author yujian
 */
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "A", tags = "A")
public class KPIVillageQuotaControllerImpl implements KPIVillageQuotaController {

    /** 村考核指标 service */
    private final KPIVillageQuotaService kPIVillageQuotaService;

    /** 考核指标附加 service */
    private final DetectionIndexService detectionIndexService;

    private final KPIEvaluationService kpiEvaluationService;

    private final CadreTaskService cadreTaskService;

    private final KpiQuotaService kpiQuotaService;

    private final KPIAttachmentService kpiAttachmentService;
    private final SysDistrictService sysDistrictService;
    private final VillageCadresService villageCadresService;
    /** 村一级指标统计 service */
    private final KPIVillageStatisticsService kPIVillageStatisticsService;
    private final static String str = "";

    private final static Map<String,Map<String, Integer>> INIT_CJSJ  = new HashMap<String,Map<String, Integer>>(){{
        put("0111",new HashMap<String, Integer>(){{put("A",2);put("B",8);put("C",7);put("D",2);}});
        put("0101",new HashMap<String, Integer>(){{put("A",1);put("B",4);put("C",3);put("D",1);}});
        put("0107",new HashMap<String, Integer>(){{put("A",1);put("B",4);put("C",3);put("D",1);}});
        put("0104",new HashMap<String, Integer>(){{put("A",2);put("B",6);put("C",6);put("D",1);}});
        put("0106",new HashMap<String, Integer>(){{put("A",1);put("B",6);put("C",6);put("D",1);}});
        put("0108",new HashMap<String, Integer>(){{put("A",2);put("B",6);put("C",6);put("D",2);}});
        put("0109",new HashMap<String, Integer>(){{put("A",2);put("B",7);put("C",6);put("D",2);}});
        put("0102",new HashMap<String, Integer>(){{put("A",2);put("B",9);put("C",8);put("D",2);}});
        put("0103",new HashMap<String, Integer>(){{put("A",2);put("B",9);put("C",9);put("D",2);}});
        put("0112",new HashMap<String, Integer>(){{put("A",1);put("B",4);put("C",4);put("D",1);}});
        put("0105",new HashMap<String, Integer>(){{put("A",1);put("B",4);put("C",4);put("D",1);}});
    }};
    private final static Map<String,Map<String, Integer>> INIT_RCBX  = new HashMap<String,Map<String, Integer>>(){{
        put("0111",new HashMap<String, Integer>(){{put("A",6);put("B",9);put("C",4);}});
        put("0101",new HashMap<String, Integer>(){{put("A",3);put("B",4);put("C",2);}});
        put("0107",new HashMap<String, Integer>(){{put("A",3);put("B",4);put("C",2);}});
        put("0104",new HashMap<String, Integer>(){{put("A",5);put("B",7);put("C",3);}});
        put("0106",new HashMap<String, Integer>(){{put("A",4);put("B",7);put("C",3);}});
        put("0108",new HashMap<String, Integer>(){{put("A",5);put("B",8);put("C",3);}});
        put("0109",new HashMap<String, Integer>(){{put("A",5);put("B",9);put("C",3);}});
        put("0102",new HashMap<String, Integer>(){{put("A",6);put("B",11);put("C",4);}});
        put("0103",new HashMap<String, Integer>(){{put("A",7);put("B",11);put("C",4);}});
        put("0112",new HashMap<String, Integer>(){{put("A",3);put("B",5);put("C",2);}});
        put("0105",new HashMap<String, Integer>(){{put("A",3);put("B",5);put("C",2);}});
    }};
    @Override
    public Result<KPIVillageQuotaVO> findOne(@ApiParam(value = "村考核指标id", required = true) @PathVariable String id) {
        Optional<KPIVillageQuota> kPIVillageQuotaOptional = kPIVillageQuotaService.findOptionalById(id);
        return kPIVillageQuotaOptional.map(kPIVillageQuota -> Result.of(kPIVillageQuota.convert(KPIVillageQuotaVO.class))).orElseGet(Result::ofNotFound);
    }

    @Override
    public Result<KPIVillageQuotaVO> add(@ApiParam(value = "村考核指标 DTO", required = true) @RequestBody @Validated KPIVillageQuotaDTO kPIVillageQuotaDTO) {
        KPIVillageQuota kPIVillageQuota = kPIVillageQuotaService.save(kPIVillageQuotaDTO.convert(KPIVillageQuota.class));
        return Result.ofAddSuccess(kPIVillageQuota.convert(KPIVillageQuotaVO.class));
    }

    @Override
    public Result<KPIVillageQuotaVO> update(@ApiParam(value = "村考核指标id", required = true) @PathVariable String id,
        @ApiParam(value = "村考核指标 DTO", required = true) @RequestBody @Validated KPIVillageQuotaDTO kPIVillageQuotaDTO) {
        Optional<KPIVillageQuota> kPIVillageQuotaOptional = kPIVillageQuotaService.findOptionalById(id);
        if (!kPIVillageQuotaOptional.isPresent()) {
            return Result.ofLost();
        }
        KPIVillageQuota kPIVillageQuota = kPIVillageQuotaOptional.get();
        BeanUtils.copyProperties(kPIVillageQuotaDTO, kPIVillageQuota);
        kPIVillageQuota = kPIVillageQuotaService.save(kPIVillageQuota);
        return Result.ofUpdateSuccess(kPIVillageQuota.convert(KPIVillageQuotaVO.class));
    }

    @Override
    public Result delete(@ApiParam(value = "村考核指标id", required = true) @PathVariable String id) {
        kPIVillageQuotaService.deleteById(id);
        return Result.ofDeleteSuccess();
    }

    @Override
    public Result<List<KPIVillageQuotaVO>> list(@ApiParam(value = "村考核指标查询条件", required = true) @RequestBody KPIVillageQuotaSearchable kPIVillageQuotaSearchable,
        @ApiParam(value = "排序条件", required = true) Sort sort) {
        List<KPIVillageQuota> kPIVillageQuotaList = kPIVillageQuotaService.findAll(kPIVillageQuotaSearchable, sort);
        List<KPIVillageQuotaVO> kPIVillageQuotaVOList = KPIVillageQuota.convert(kPIVillageQuotaList, KPIVillageQuotaVO.class);

        return Result.of(kPIVillageQuotaVOList);
    }

    @Override
    public Result<Page<KPIVillageQuotaVO>> page(@ApiParam(value = "村考核指标查询条件", required = true) @RequestBody KPIVillageQuotaSearchable kPIVillageQuotaSearchable,
        @ApiParam(value = "分页参数", required = true) Pageable pageable) {
        Page<KPIVillageQuota> kPIVillageQuotaPage = kPIVillageQuotaService.findAll(kPIVillageQuotaSearchable, pageable);
        Page<KPIVillageQuotaVO> kPIVillageQuotaVOPage = KPIVillageQuota.convert(kPIVillageQuotaPage, KPIVillageQuotaVO.class);
        return Result.of(kPIVillageQuotaVOPage);
    }



    @GetMapping("/loadVillageAllQuota")
    public Result<List<Map<String, Object>>> loadAllVillageAllQuota(@NonNull String districtId, @NonNull String taskId,  @NonNull String taskYear, @Nonnull String departDistrictId) {
        String scoringQuotaDistrictId = districtId.substring(0, 4);
        if (!StringUtils.isEmpty(departDistrictId)) {
            scoringQuotaDistrictId = departDistrictId;
        }
        CadreTask byId = cadreTaskService.findById(taskId);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(CadreTask.class);
        detachedCriteria.add(Restrictions.eq("taskYear", byId.getTaskYear()));
        detachedCriteria.add(Restrictions.eq("type", "考核指标内容制定"));
        List<CadreTask> all = cadreTaskService.findAll(detachedCriteria);
        if (all.size() == 0) {
            return Result.of(500, "对应考核指标任务不存在！");
        }
        List<Map<String, Object>> res = new ArrayList<>();
        CadreTask quotaTask = all.get(0);
        String quotaTaskId = quotaTask.getId();

        DetachedCriteria detachedCriteria1 = DetachedCriteria.forClass(KpiQuota.class);
        detachedCriteria1.add(Restrictions.like("quotaScoringDepartId", scoringQuotaDistrictId, MatchMode.ANYWHERE));
        detachedCriteria1.add(Restrictions.eq("quotaLevel", "1"));
        detachedCriteria1.add(Restrictions.eq("quotaYear", taskYear));
        detachedCriteria1.addOrder(Order.asc("quotaId"));
        List<KpiQuota> all1 = kpiQuotaService.findAll(detachedCriteria1);
        for (KpiQuota item : all1) {
            String quotaId = item.getQuotaId();
            Map<String, Object> temps = new HashMap<>();
            KpiQuota byQuotaId = kpiQuotaService.findByQuotaId(quotaId);
            List<Map<String, Object>> maps = new LinkedList<>();
            maps = kPIVillageQuotaService.buildWatchQuotaData(districtId, quotaTaskId, taskId, quotaTask.getTaskYear(), quotaId, scoringQuotaDistrictId,all1);

            temps.put("quotaId", quotaId);
            temps.put("quotaName", byQuotaId.getQuotaName());
            temps.put("quotaScore", byQuotaId.getQuotaScore());
            temps.put("isSetWeight", byQuotaId.getIsSetWeight());
            temps.put("attachment", kpiAttachmentService.findByQuota(item.getQuotaId(), scoringQuotaDistrictId, null, taskId));
            temps.put("kpiQuotas", maps);

            res.add(temps);
        }

        return Result.of(res);
    }
    @GetMapping("/changeState")
    public Result changeState(@NonNull String districtId, @NonNull String taskYear) {
        Map<String,Boolean> map = new HashMap<>();
        //1.查询此部门or镇打分的项目
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(KpiQuota.class);
        detachedCriteria.add(Restrictions.like("quotaScoringDepartId", districtId, MatchMode.ANYWHERE));
        detachedCriteria.add(Restrictions.eq("quotaLevel","2"));
        detachedCriteria.add(Restrictions.eq("quotaYear",taskYear));
        List<KpiQuota> all = kpiQuotaService.findAll(detachedCriteria);
        List<String> list = all.stream().map(KpiQuota::getQuotaId).collect(Collectors.toList());
        //2.判断任务执行人是部门还是镇
        if ("0144".equals(districtId)||"0143".equals(districtId)||"0145".equals(districtId) ||"0148".equals(districtId)){
            //部门执行人
            kPIVillageQuotaService.updateStateByTownQuotaId(list);
        }else {
            //镇执行人
            kPIVillageQuotaService.updateStateByTownQuotaIdAndParentDistrictId(list,districtId);
        }
        map.put("res",true);
        return Result.of(map);
    }
    @GetMapping("/getAllByTownQuotaId")
    public Result<List<KPIVillageQuotaVO>> loadAllVillageAllQuota(@NonNull String townQuotaId) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(KPIVillageQuota.class);
        detachedCriteria.add(Restrictions.eq("townQuotaId", townQuotaId));
        detachedCriteria.addOrder(Order.asc("districtId"));
        List<KPIVillageQuota> all = kPIVillageQuotaService.findAll(detachedCriteria);
        List<KPIVillageQuotaVO> convert = KPIVillageQuota.convert(all, KPIVillageQuotaVO.class);
        return Result.of(convert);
    }
    @GetMapping("/degreeCheck/{type}/{districtId}/{taskId}/{degree}")
    public Result<Object> degreeCheck(@PathVariable String type,@PathVariable String districtId,@PathVariable String taskId,@PathVariable String degree) {
        Map<String,Boolean> map = new HashMap<String,Boolean>(){{
            put("res",true);
        }};
        if (type.equals("rcgz")){
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DetectionIndex.class);
            detachedCriteria.add(Restrictions.eq("taskId",taskId));
            detachedCriteria.add(Restrictions.like("districtId",districtId, MatchMode.START));
            detachedCriteria.add(Restrictions.eq("field2",degree));
            int total = detectionIndexService.getTotalCount(detachedCriteria);
            if (INIT_RCBX.containsKey(districtId)){
                if (INIT_RCBX.get(districtId).get(degree) - total <= 0){
                    map.put("res",false);
                    return Result.of(map);
                }
            }

            return Result.of(map);
        }else {
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DetectionIndex.class);
            detachedCriteria.add(Restrictions.eq("taskId",taskId));
            detachedCriteria.add(Restrictions.like("districtId",districtId, MatchMode.START));
            detachedCriteria.add(Restrictions.eq("villageLevelAchievements",degree));
            int total = detectionIndexService.getTotalCount(detachedCriteria);
            if (INIT_CJSJ.containsKey(districtId)){
                if (INIT_CJSJ.get(districtId).get(degree) - total <= 0){
                    map.put("res",false);
                    return Result.of(map);
                }
            }
            return Result.of(map);
        }
    }
    @PostMapping("/scoring")
    @Transactional
    public Result scoring(@Nonnull String userDistrictId,@Nonnull String taskId,@Nonnull @RequestBody List<ScoringDTO> scoringDTOS) {
        boolean f1 = true,f2 = true,f3 = true,f0 = true;
        KPIVillageQuotaHasScoringVO kpiVillageQuotaHasScoringVO = new KPIVillageQuotaHasScoringVO();
        //默认只有一条
        for (ScoringDTO item : scoringDTOS) {
            String score = item.getScore();
            if (StringUtils.isEmpty(score)) {
                score = null;
            }
//            String weight = item.getWeight();
//            if (StringUtils.isEmpty(weight)) {
//                weight = "0";
//            }
//            BigDecimal multiply = new BigDecimal(score).multiply(new BigDecimal(weight));
            kPIVillageQuotaService.updateScoreById(score, score, item.getId());



            DetectionIndex detectionIndex = detectionIndexService.findByDistrictIdAndTaskId(item.getDistrictId(), taskId);
            if (detectionIndex == null) {
                detectionIndex = new DetectionIndex();
            }
            String[] nullPropertyNames = getNullPropertyNames(item);
            List<String> strings = Arrays.asList(nullPropertyNames);
            List<String> ignoreProperties = new ArrayList<>(strings);
            ignoreProperties.add("id");
            BeanUtils.copyProperties(item, detectionIndex, ignoreProperties.toArray(nullPropertyNames));
            detectionIndexService.save(detectionIndex);

            if (item.getKpiEvaluations() == null) {
                continue;
            }
            for (KPIEvaluationDTO subItem : item.getKpiEvaluations()) {
                subItem.setVillageQuotaId(item.getId());
                kpiEvaluationService.save(subItem.convert(KPIEvaluation.class));
            }
            KPIVillageQuota kpiVillageQuota = kPIVillageQuotaService.findById(item.getId());
            String districtId = kpiVillageQuota.getDistrictId();
            String parentDistrictId = kpiVillageQuota.getParentDistrictId();

            //0.获取一级指标是否存在未打分
            List<KpiQuota> kpiQuotas = kpiQuotaService.findAllByParentQuotaIdOrderByQuotaIdAsc(kpiVillageQuota.getParentQuotaId());
            String str = "";
            for (KpiQuota kpiQuota : kpiQuotas){
                if (kpiQuota.getQuotaScoringDepartId().contains(userDistrictId)){
                    str += "'"+ kpiQuota.getQuotaId()+"',";
                }

            }
            String sql0 = "SELECT (cast (count(1) as VARCHAR)) as unaccomplished FROM KPI_village_Quota " +
                    "WHERE (score = '' or score is null) and townQuotaId like '"+ kpiVillageQuota.getParentQuotaId() +"%'";

            if (!("0144".equals(userDistrictId)||"0143".equals(userDistrictId)||"0145".equals(userDistrictId) || "0148".equals(districtId))){
                sql0 += " and parentDistrictId = " + userDistrictId;
            }
            if (StringUtils.isNotBlank(str)){
                sql0 += " and townQuotaId in (" + str.substring(0,str.length()-1) + ")";
            }
            KPIVillageQuotaDistrictVO kpiVillageQuotaDistrictVO0 = kPIVillageQuotaService.findBySql(KPIVillageQuotaDistrictVO.class, sql0);
            if (Integer.valueOf(kpiVillageQuotaDistrictVO0.getUnaccomplished()) > 0){
                f0 = false;
            }

            //1.获取二级指标是否存在未打分
            String townQuoataId = kpiVillageQuota.getTownQuotaId();
            String sql = "SELECT (cast (count(1) as VARCHAR)) as unaccomplished FROM KPI_village_Quota " +
                    "WHERE (score = '' or score is null) and townQuotaId = "+ townQuoataId;
            if (!("0144".equals(userDistrictId)||"0143".equals(userDistrictId)||"0145".equals(userDistrictId) || "0148".equals(districtId))){
                sql += " and parentDistrictId = " + parentDistrictId;
            }
            KPIVillageQuotaDistrictVO kpiVillageQuotaDistrictVO = kPIVillageQuotaService.findBySql(KPIVillageQuotaDistrictVO.class, sql);
            if (Integer.valueOf(kpiVillageQuotaDistrictVO.getUnaccomplished()) > 0){
                f1 = false;
            }
            //2.获取镇是否存在未打分
            sql += " and parentDistrictId = " + parentDistrictId;
            KPIVillageQuotaDistrictVO kpiVillageQuotaDistrictVO1 = kPIVillageQuotaService.findBySql(KPIVillageQuotaDistrictVO.class, sql);
            if (Integer.valueOf(kpiVillageQuotaDistrictVO1.getUnaccomplished()) > 0){
                f2 = false;
            }
            //3.获取村是否存在未打分
            sql += " and districtId = " + districtId;
            KPIVillageQuotaDistrictVO kpiVillageQuotaDistrictVO2 = kPIVillageQuotaService.findBySql(KPIVillageQuotaDistrictVO.class, sql);
            if (Integer.valueOf(kpiVillageQuotaDistrictVO2.getUnaccomplished()) > 0){
                f3 = false;
            }

            kpiVillageQuotaHasScoringVO.setQuotaHasScoring(f1);
            kpiVillageQuotaHasScoringVO.setTownHasScoring(f2);
            kpiVillageQuotaHasScoringVO.setVillageHasScoring(f3);
            kpiVillageQuotaHasScoringVO.setDistrictId(districtId);
            kpiVillageQuotaHasScoringVO.setParentDistrictId(parentDistrictId);
            kpiVillageQuotaHasScoringVO.setTownQuotaHasScoring(f0);
            kpiVillageQuotaHasScoringVO.setVillageQuotaId(townQuoataId);
            kpiVillageQuotaHasScoringVO.setTownQuotaId(kpiVillageQuota.getParentQuotaId());
        }
        return Result.of(kpiVillageQuotaHasScoringVO);
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    @GetMapping("/getFullScore")
    public Result<Map> getFullScore(String taskYear, String percent) {
        String sql = "SELECT\n" +
                "\t* \n" +
                "FROM\n" +
                "\t(\n" +
                "\tSELECT\n" +
                "\t\t* ,\n" +
                "\t\tROUND( CAST ( fullTotal AS FLOAT ) / CAST ( total AS FLOAT ), 2 ) AS fullRatio \n" +
                "\tFROM\n" +
                "\t\t(\n" +
                "\t\tSELECT COUNT\n" +
                "\t\t\t( 1 ) AS total,\n" +
                "\t\t\tSUM ( CASE kvq.scoreEnd WHEN ktq.score THEN 1 ELSE 0 END ) AS fullTotal,\n" +
                "\t\t\tktq.quotaName,\n" +
                "\t\t\tktq.parentQuotaId,\n" +
                "\t\t\tktq.districtName \n" +
                "\t\tFROM\n" +
                "\t\t\tKPI_village_Quota kvq\n" +
                "\t\t\tLEFT JOIN KPI_Town_Quota ktq ON ktq.id = kvq.townQuotaId \n" +
                "\t\tWHERE\n" +
                "\t\t\tkvq.parentQuotaId LIKE '" + taskYear+ "%' \n" +
                "\t\tGROUP BY\n" +
                "\t\t\tktq.id,\n" +
                "\t\t\tktq.quotaName,\n" +
                "\t\t\tktq.parentQuotaId,\n" +
                "\t\t\tktq.districtName \n" +
                "\t\t) a \n" +
                "\t) b \n" +
                "WHERE\n" +
                "\tfullRatio >= '" + percent +"'";
        List<FullScoreVO> fullScoreVOS = kPIVillageQuotaService.findAllBySql(FullScoreVO.class, sql);

        Map<String, Integer> map = new HashMap<>();
        ArrayList<FullScoreVO> actualVillage = new ArrayList<>();
        Set<FullScoreVO> noActualVillage = new HashSet<>();
        for (FullScoreVO item : fullScoreVOS) {
            if (!map.containsKey(item.getDistrictName())) {
                map.put(item.getDistrictName(), 0);
            }
            Integer integer = map.get(item.getDistrictName());
            map.put(item.getDistrictName(), ++integer);
            if (item.getParentQuotaId().contains(taskYear + "02")) {
                actualVillage.add(item);
            } else {
                noActualVillage.add(item);
            }
        }
        actualVillage.addAll(noActualVillage);
        return Result.of(new HashMap(){{put("townCount", map);put("quotas", actualVillage);}});
    }
    /**
     * 查询镇列表
     *
     * @param kPIVillageQuotaSearchable 村考核指标查询条件
     * @return 查询镇列表
     */
    @PostMapping("/findDistrictByTownQuotaId")
    public Result<List<KPIVillageQuotaDistrictVO>> findDistrictByTownQuotaId(@ApiParam(value = "村考核指标查询条件", required = true) @RequestBody KPIVillageQuotaSearchable kPIVillageQuotaSearchable) {
        String townQuoataId = kPIVillageQuotaSearchable.getTownQuotaId();
        String sql = "SELECT parentDistrictId as districtId ,(cast (SUM(CASE WHEN (score IS NULL or score = '') THEN 1 ELSE 0 END) as VARCHAR)) as unaccomplished FROM KPI_village_Quota WHERE townQuotaId = "+ townQuoataId;
        if (StringUtils.isNotBlank(kPIVillageQuotaSearchable.getDistrictId())){
            sql += " and parentDistrictId = "+ kPIVillageQuotaSearchable.getDistrictId();
        }
        sql += " GROUP BY parentDistrictId ORDER BY parentDistrictId ASC";
        List<KPIVillageQuotaDistrictVO> kpiVillageQuotaDistrictVOS = kPIVillageQuotaService.findAllBySql(KPIVillageQuotaDistrictVO.class, sql);
        List<SysDistrict> villages = sysDistrictService.findAllTowns();
        Map<String,String> map = villages.stream().collect(Collectors.toMap(SysDistrict::getDistrictId,SysDistrict::getDistrictName));
        for (KPIVillageQuotaDistrictVO k : kpiVillageQuotaDistrictVOS){
            if (Integer.valueOf(k.getUnaccomplished())>0){
                k.setFlag(false);
            }else {
                k.setFlag(true);
            }
            k.setDistrictName(map.get(k.getDistrictId()));
            k.setTownQuotaId(townQuoataId);
        }
        return Result.of(kpiVillageQuotaDistrictVOS);
    }

    /**
     * 查询村列表
     *
     * @param kPIVillageQuotaSearchable 村考核指标查询条件
     * @return 查询村列表
     */
    @PostMapping("/findDistrictByTownQuotaIdAndDistrictId")
    public Result<List<KPIVillageQuotaDistrictVO>> findDistrictByTownQuotaIdAndDistrictId(@RequestBody KPIVillageQuotaSearchable kPIVillageQuotaSearchable) {
        String sql = "SELECT districtId ,districtName,(cast (SUM(CASE WHEN (score IS NULL or score = '') THEN 1 ELSE 0 END) as VARCHAR)) as unaccomplished FROM KPI_village_Quota WHERE townQuotaId = "+ kPIVillageQuotaSearchable.getTownQuotaId() +
                " and parentDistrictId = "+ kPIVillageQuotaSearchable.getDistrictId();
        List<String> villageWithoutCadres = villageCadresService.findVillageWithoutCadres();
        if (villageWithoutCadres.size() > 0) {
            sql += " and districtId not in (" + String.join(",", villageWithoutCadres) + ")";
        }
        sql += " GROUP BY districtId ,districtName ORDER BY districtId ASC";
        List<KPIVillageQuotaDistrictVO> kpiVillageQuotaDistrictVOS = kPIVillageQuotaService.findAllBySql(KPIVillageQuotaDistrictVO.class, sql);
        //此处由于前端太懒，让我给他传过去
        for (KPIVillageQuotaDistrictVO k : kpiVillageQuotaDistrictVOS){
            if (Integer.valueOf(k.getUnaccomplished())>0){
                k.setFlag(false);
            }else {
                k.setFlag(true);
            }
            k.setTownQuotaId(kPIVillageQuotaSearchable.getTownQuotaId());
        }
        return Result.of(kpiVillageQuotaDistrictVOS);
    }
    @GetMapping("/getAll/{year}")
    @ApiOperation(value = "按年份查询打分情况", notes = "按年份查询打分情况", position = 1)
    public Result getAll(@PathVariable String year){

        CadreTask task = cadreTaskService.getCurrentTaskByType("综合年度考核", year, "");
        if (null == task) {
            return Result.of(500, "任务不存在");
        }

        //获取所有村级组织
        List<SysDistrict> sysDistricts = sysDistrictService.findAllByDistrictLevelAndDistrictType(3,"Party");

        //获取所有指标名称
        DetachedCriteria detachedCriteria1 = DetachedCriteria.forClass(KpiQuota.class);
        detachedCriteria1.add(Restrictions.like("quotaId",year,MatchMode.START));
        List<KpiQuota> kpiQuotas = kpiQuotaService.findAll(detachedCriteria1);
        Stream<KpiQuota> stream = kpiQuotas.stream();

        //筛选出二级指标，按照指标Id正序排序
        List<KpiQuota> villageKpiQuotas = stream.filter(kpiQuota -> kpiQuota.getQuotaId().length() > 6).collect(Collectors.toList());
        villageKpiQuotas = villageKpiQuotas.stream().sorted(Comparator.comparing(KpiQuota::getQuotaId)).collect(Collectors.toList());

        //获取所有打分指标名称
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(KPIVillageQuota.class);
        detachedCriteria.add(Restrictions.like("townQuotaId", year,MatchMode.START));
        List<KPIVillageQuota> all = kPIVillageQuotaService.findAll(detachedCriteria);
        Map<String,List<KPIVillageQuota>> kpiVillageQuotaMap = all.stream().collect(Collectors.groupingBy(KPIVillageQuota::getDistrictId));

        String countSql = "select from KPI_village_Quota where townQuotaId like '"+year+"%' group by districtId";

        //获取所有村书记 1.去统计表中查询，统计表中没有去村书记表中取
        String sql = "select districtId,cadresName from KPI_Village_Statistics where quotaLevel = '0' and quotaYear ='"+year+"' group by districtId,cadresName ";
        List<KPIVillageStatisticsVO> list = kPIVillageStatisticsService.findAllBySql(KPIVillageStatisticsVO.class,sql);
        Map<String,String> map;
        if (list == null || list.size() == 0){
            DetachedCriteria villageCadresDDetachedCriteria = DetachedCriteria.forClass(VillageCadres.class);
            villageCadresDDetachedCriteria.add(Restrictions.eq("hasRetire","0"));
            villageCadresDDetachedCriteria.add(Restrictions.eq("cadresType","SECRETARY"));
            List<VillageCadres> villageCadres = villageCadresService.findAll(villageCadresDDetachedCriteria);
            map = villageCadres.stream().collect(Collectors.toMap(VillageCadres::getDistrictId,VillageCadres::getName));
        }else {
            map = list.stream().collect(Collectors.toMap(KPIVillageStatisticsVO::getDistrictId,KPIVillageStatisticsVO::getCadresName));
        }
        //需要组合的数据结构
        List<List<String>> res = new ArrayList<>();

        //第一行为字段名
        List<String> frist = new ArrayList<>();
        frist.add("镇级组织名称");
        frist.add("村级组织名称");
        frist.add("村书记名称");
        frist.addAll(villageKpiQuotas.stream().map(kpiQuota -> kpiQuota.getQuotaName()+"（"+kpiQuota.getQuotaScore()+"分）").collect(Collectors.toList()));
        frist.add("合计");
        res.add(frist);

        for (SysDistrict s : sysDistricts){
            if (kpiVillageQuotaMap.containsKey(s.getDistrictId())){
                List<String> content = new ArrayList<>();
                content.add(s.getParentName());
                content.add(s.getDistrictName());
                content.add(map.get(s.getDistrictId()));
                List<KPIVillageQuota> kpiVillageQuotas = kpiVillageQuotaMap.get(s.getDistrictId()).stream().sorted(Comparator.comparing(KPIVillageQuota::getTownQuotaId)).collect(Collectors.toList());
                List<String> strings = new ArrayList<>();

                BigDecimal bigDecimal = BigDecimal.ZERO;
                for (KPIVillageQuota item : kpiVillageQuotas) {
                    if (item.getTownQuotaId().contains("0701")) {
                        DetectionIndex detectionIndex = detectionIndexService.findByDistrictIdAndTaskId(s.getDistrictId(), task.getId());
                        if (null != detectionIndex) {
                            strings.add(detectionIndex.getField1());
                        }
                    } else {
                        strings.add(item.getScore());
                        if (StringUtils.isNotBlank(item.getScore())){
                            bigDecimal = bigDecimal.add(new BigDecimal(item.getScore())).setScale(3, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }

                content.addAll(strings);
                content.add(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                res.add(content);
            }
        }
        return Result.of(res);
    }

    @GetMapping("/exportAll/{year}")
    @ApiOperation(value = "按年份查询打分情况", notes = "按年份查询打分情况", position = 1)
    public Result exportAll(@PathVariable String year){
        CadreTask task = cadreTaskService.getCurrentTaskByType("综合年度考核", year, "");
        if (null == task) {
            return Result.of(500, "任务不存在");
        }
        //获取所有村级组织
        List<SysDistrict> sysDistricts = sysDistrictService.findAllByDistrictLevelAndDistrictType(3,"Party");

        //获取所有指标名称
        DetachedCriteria detachedCriteria1 = DetachedCriteria.forClass(KpiQuota.class);
        detachedCriteria1.add(Restrictions.like("quotaId",year,MatchMode.START));
        List<KpiQuota> kpiQuotas = kpiQuotaService.findAll(detachedCriteria1);
        Stream<KpiQuota> stream = kpiQuotas.stream();

        //筛选出二级指标，按照指标Id正序排序
        List<KpiQuota> villageKpiQuotas = stream.filter(kpiQuota -> kpiQuota.getQuotaId().length() > 6).collect(Collectors.toList());
        villageKpiQuotas = villageKpiQuotas.stream().sorted(Comparator.comparing(KpiQuota::getQuotaId)).collect(Collectors.toList());

        //获取所有打分指标名称
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(KPIVillageQuota.class);
        detachedCriteria.add(Restrictions.like("townQuotaId", year,MatchMode.START));
        List<KPIVillageQuota> all = kPIVillageQuotaService.findAll(detachedCriteria);
        Map<String,List<KPIVillageQuota>> kpiVillageQuotaMap = all.stream().collect(Collectors.groupingBy(KPIVillageQuota::getDistrictId));

        String countSql = "select from KPI_village_Quota where townQuotaId like '"+year+"%' group by districtId";

        //获取所有村书记 1.去统计表中查询，统计表中没有去村书记表中取
        String sql = "select districtId,cadresName from KPI_Village_Statistics where quotaLevel = '0' and quotaYear ='"+year+"' group by districtId,cadresName ";
        List<KPIVillageStatisticsVO> list = kPIVillageStatisticsService.findAllBySql(KPIVillageStatisticsVO.class,sql);
        Map<String,String> map;
        if (list == null || list.size() == 0){
            DetachedCriteria villageCadresDDetachedCriteria = DetachedCriteria.forClass(VillageCadres.class);
            villageCadresDDetachedCriteria.add(Restrictions.eq("hasRetire","0"));
            villageCadresDDetachedCriteria.add(Restrictions.eq("cadresType","SECRETARY"));
            List<VillageCadres> villageCadres = villageCadresService.findAll(villageCadresDDetachedCriteria);
            map = villageCadres.stream().collect(Collectors.toMap(VillageCadres::getDistrictId,VillageCadres::getName));
        }else {
            map = list.stream().collect(Collectors.toMap(KPIVillageStatisticsVO::getDistrictId,KPIVillageStatisticsVO::getCadresName));
        }
        //需要组合的数据结构
        List<Object[]> res = new ArrayList<>();

        //第一行为字段名
        List<String> frist = new ArrayList<>();
        frist.add("序号");
        frist.add("镇级组织名称");
        frist.add("村级组织名称");
        frist.add("村书记名称");
        frist.addAll(villageKpiQuotas.stream().map(kpiQuota -> kpiQuota.getQuotaName()+"（"+kpiQuota.getQuotaScore()+"分）").collect(Collectors.toList()));
        for (SysDistrict s : sysDistricts){
            if (kpiVillageQuotaMap.containsKey(s.getDistrictId())){
                List<String> content = new ArrayList<>();
                content.add(str);
                content.add(s.getParentName());
                content.add(s.getDistrictName());
                content.add(map.get(s.getDistrictId()));
                List<KPIVillageQuota> kpiVillageQuotas = kpiVillageQuotaMap.get(s.getDistrictId()).stream().sorted(Comparator.comparing(KPIVillageQuota::getTownQuotaId)).collect(Collectors.toList());
                List<String> strings = new ArrayList<>();

                BigDecimal bigDecimal = BigDecimal.ZERO;
                for (KPIVillageQuota item : kpiVillageQuotas) {
                    if (item.getTownQuotaId().contains("0701")) {
                        DetectionIndex detectionIndex = detectionIndexService.findByDistrictIdAndTaskId(s.getDistrictId(), task.getId());
                        if (null != detectionIndex) {
                            strings.add(detectionIndex.getField1());
                        }
                    } else {
                        strings.add(item.getScore());
                        if (StringUtils.isNotBlank(item.getScore())){
                            bigDecimal = bigDecimal.add(new BigDecimal(item.getScore())).setScale(3, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }
                content.addAll(strings);
                content.add(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                res.add(content.toArray(new String[content.size()]));
            }
        }
        String url = kPIVillageQuotaService.exportAll(frist.toArray(new String[frist.size()]),res);
        Map map1 = new HashMap();
        map1.put("url",url);
        return Result.of(map1);
    }

    @GetMapping("/villageCollectiveEconomy/{districtID}")
    @ApiOperation(value = "查询年度村集体五项收入", notes = "查询年度村集体五项收入", position = 1)
    public Result villageCollectiveEconomy(@PathVariable String districtID){
        List<Map<String,Object>> list = new ArrayList<>();
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(CadreTask.class);
        detachedCriteria.add(Restrictions.eq("type","综合年度考核"));
        detachedCriteria.add(Restrictions.ne("taskYear", String.valueOf(LocalDate.now().getYear() - 1)));
        detachedCriteria.add(Restrictions.ne("taskYear", "2019"));
        detachedCriteria.addOrder(Order.desc("taskYear"));
        List<CadreTask> cadreTasks = cadreTaskService.findAll(detachedCriteria);
        for (CadreTask cadreTask : cadreTasks){
            DetectionIndex index = detectionIndexService.findByDistrictIdAndTaskId(districtID,cadreTask.getId());
            Map<String,Object> map = new HashMap<>();
            if ((LocalDate.now().getYear() - 2) == Integer.parseInt(cadreTask.getTaskYear())){
                Map<String,Object> map1 = new HashMap<>();
                map1.put(cadreTask.getTaskYear(),index.getCurrentYearEconomicIncome());
                list.add(map1);
            }
            map.put(String.valueOf(Integer.parseInt(cadreTask.getTaskYear())-1),index.getLastYearEconomicIncome());
            list.add(map);
        }
        return Result.of(list);
    }
}
